package com.cyw.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.cyw.mapper.RoleMapper;
import com.cyw.mapper.UserMapper;
import com.cyw.pojo.Permission;
import com.cyw.pojo.Role;
import com.cyw.pojo.User;
import com.cyw.utils.RedisUtil;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token=request.getHeader("Authorization");
        //如果验证token失败，并且方法注明了Authorization，返回401错误
        if (token == null) {
            sendResponse(response, "-1", "need login");
            return false;
        }
        RedisUtil redisUtil = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(RedisUtil.class);
        String json = redisUtil.get(token);
        User user = JSONObject.parseObject(json, User.class);
        if (user == null) {
            sendResponse(response, "-1", "token error");
            return false;
        }
        String method = request.getMethod();
        String uri = request.getRequestURI();
        if (!checkPermission(user, method, uri, request)) {
            sendResponse(response, "-1", "该用户没有权限");
            return false;
        }
        return true;
    }

    public boolean checkPermission(User user, String method, String uri, HttpServletRequest request) {
        UserMapper userMapper = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(UserMapper.class);
        RoleMapper roleMapper = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(RoleMapper.class);
        Set<Role> roles = userMapper.getUserRoles(user.getUsername());
        for (Role role : roles) {
            Set<Permission> permissions = roleMapper.getRolePermissions(role.getRoleCode());
            for (Permission permission : permissions) {
                boolean equals = uri.contains(permission.getPath()) && permission.getPermissionName().contains(method);
                if (equals) return true;
            }
        }
        return false;
    }

    public void sendResponse(HttpServletResponse response, String errorCode, String msg) throws IOException {
        //设置response状态
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //返回的数据
        JSONObject res = new JSONObject();
        res.put("errorCode", errorCode);
        res.put("msg", msg);
        PrintWriter out = null;
        out = response.getWriter();
        out.write(res.toString());
        out.flush();
        out.close();
    }
}
